import {fetchPermission} from "@/api/index";
import {recursionRouter, setDefaultRoute} from "@/utils/recursion-router";
import dynamicRouter from "@/router/dynamic-router";
import router, {DynamicRoutes} from "@/router";

export default {
    namespaced: true,
    state: {
        permissionList: null,
        sidebarMenu: [],
        currentMenu: ""
    },
    getters: {},
    mutations: {
        SET_PERMISSION(state, routes) {
            state.permissionList = routes;
        },
        CLEAR_PERMSSION(state) {
            state.permissionList = null;
        },
        SET_MENU(state, menu) {
            state.sidebarMenu = menu;
        },
        CLEAR_MENU(state) {
            state.sidebarMenu = []
        }
    },
    actions: {
        async FETCH_PERMISSION({commit, state}) {
            console.log('FETCH_PERMISSION')
            let data = await fetchPermission();
            let permissionList = data.data;
            let routes = recursionRouter(permissionList,dynamicRouter);
            let MainContainer = DynamicRoutes.find(v => v.path === "");
            // 将动态创建的路由给 MainContainer
            let children = MainContainer.children;
            children.push(...routes)
            // 生成菜单
            commit("SET_MENU",children);
            // 设置默认路由
            setDefaultRoute([MainContainer]);
            // 初始化路由
            let initialRoutes = router.options.routes;
            //
            router.addRoutes(DynamicRoutes);
            commit("SET_PERMISSION",[ ...initialRoutes , ...DynamicRoutes])

        }
    }
}
